<template>
  <el-dialog v-model="visible" :title="isEdit ? '编辑议程' : '新增议程'" width="50%">
    <el-form ref="formRef" label-width="120px" :model="form" :rules="rules">
      <el-form-item label="活动ID" prop="activityId">
        <el-input v-model="form.activityId" placeholder="请输入活动ID" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" placeholder="请输入备注" />
      </el-form-item>
      <el-form-item label="内容" prop="filePreview">
        <quill-editor v-model="form.filePreview" placeholder="请输入内容" @blur="handleEditorBlur" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { computed, ref, watch } from 'vue'
import QuillEditor from '~/src/components/quill/QuillEditor.vue'
import type { Agenda } from '../config'

const props = defineProps<{
  modelValue: boolean
  formData?: Partial<Agenda>
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'submit', formData: Agenda): void
}>()

const visible = ref(props.modelValue)
const formRef = ref<FormInstance>()
const form = ref<Partial<Agenda>>({
  activityId: '',
  remark: '',
  filePreview: '',
})

const isEdit = computed(() => !!props.formData?.id)

const rules = {
  activityId: [{ required: true, message: '请输入活动ID', trigger: 'blur' }],
  filePreview: [{ required: true, message: '请输入内容', trigger: 'blur' }],
}

watch(
  () => props.modelValue,
  (val) => {
    visible.value = val
  }
)

watch(visible, (val) => {
  emit('update:modelValue', val)
  if (!val) {
    resetForm()
  }
})

watch(
  () => props.formData,
  (val) => {
    if (val) {
      form.value = { ...val }
    }
  },
  { immediate: true }
)

const handleEditorBlur = () => {
  formRef.value?.validateField('filePreview')
}

const resetForm = () => {
  form.value = {
    activityId: '',
    remark: '',
    filePreview: '',
  }
  formRef.value?.resetFields()
}

const closeDialog = () => {
  visible.value = false
}

const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate((valid) => {
    if (valid) {
      emit('submit', form.value as Agenda)
      visible.value = false
    }
  })
}
</script>

<style scoped>
.dialog-footer {
  padding: 20px 0 0;
  text-align: right;
}
</style>
